// pages/acceptParticulars/acceptParticulars.js
import { uploadAliyun } from '../../utils/UploadAliyun';
import api from "../../config/api";
import request from "../../utils/request";
import { shareOptions } from "../../utils/access";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 物品id
    id:'',
    // 物品详情的数据
    goodsData:{},
    isShowTabs:'1',
    isShowHover:'1',
    isShowRecord:false,
    // 表单下拉框区域
    accounts: [],
    accountIndex: 0,
    accountsSex:[],
    accountIndexSex:0,
    accountsSeason:[],
    accountIndexSeason:0,
    // 上传照片的变量
    picPath: null,
    // 弹出层
    isShowClass: '1',
    // 选择分类标签的数据
    changeListData:[],
    // 自定义标签的数据
    customTabsItem:[],
    // 编辑&保存按钮的显示
    isEditorShow:true,
    // 控制添加表单对话框
    dialogShow:false,
    buttons: [{text: '确定'}],
    addInputValue:'',
    // 空间列表
    spanceData:[],
    // 容器列表
    goodsData2:[],
    // 用户的标签列表
    userTabData:[],
    // 被删除的数据
    delData:[],
    // 空间默认选中
    spanceTitleIndex:0,
    // 容器默认选中
    goodsTitleIndex:0,
    // 弹出层出现时控制外层是否滚动
    openIndex:false,
    // 备注文本框的内容
    bzValue:''
  },
  // 删除标签的ID数组
  delTabs:[],
  // 给后台返回的表单
  parTicularsForm:{
    containerId:'',
    spaceId:'',
    id:'',
    itemImgUrl:'',
    itemRemark:'',
    bz:'',
    labelIdList:[],
    itemSeason:0,
    itemSex:0,
    itemType:0
  },
  // 获得空间数据列表
   async getSpanceData(){
     const { data  }= await request.get(api.spaceList)
     const newSpanceList =  data.spaceData.filter(item=>{
       if (item.containerList.length>0){
         return item
       }
     })
     const arr = newSpanceList.map((item)=>({
       id: item.id,
       name:item.spaceName,
       picUrls: (item.picUrl).split(',')
     }))
    //  判断用户选中的是第几个空间
     let spanceIndex  = newSpanceList.findIndex(item=>{
       return item.id === this.data.goodsData.spaceId
     })
     if (spanceIndex === -1) {
      spanceIndex = 0
     }
     this.setData({
       spanceTitleIndex:spanceIndex,
       spanceData:arr,
     })
  },
  // 获得容器数据列表
   async getGoodsData(id){
     const { data } = await request.get(api.containerList,{
      storageSpaceId:id
     })
     console.log(data)
     const arr = (data).map((item)=>({
      id:item.id,
      name:item.containerName,
      picUrls: (item.picUrl).split(',')
    }))
    // 默认选中第几个容器
    let goodsIndex = data.findIndex(item=>{
      return item.id === this.data.goodsData.containerId
    })
    if(goodsIndex=== -1){
      goodsIndex = 0
    }
    this.parTicularsForm.containerId = arr[0].id
    this.setData({
      goodsTitleIndex:goodsIndex,
      goodsData2:arr,
    })
   },
  // 下拉菜单表单改变触发的回调
  bindCountryChange:function(e){
    console.log(e)
    const a = parseInt(e.detail.value)
    this.setData({
      accountIndex: e.detail.value
    })
    console.log(this.data.accounts[this.data.accountIndex])
    this.parTicularsForm.itemType = a + 1
  },
  // 下拉菜单性别改变触发的回调
  bindCountryChangeSex:function(e){
    const a = parseInt(e.detail.value)
    this.setData({
      accountIndexSex: e.detail.value
    })
    console.log(this.data.accountsSex[this.data.accountIndexSex])
    this.parTicularsForm.itemSex = a + 1
  },
    // 下拉菜单季节改变触发的回调
  bindCountryChangeSeason:function(e){
    const a = parseInt(e.detail.value)
    this.setData({
      accountIndexSeason: e.detail.value
    })
    console.log(this.data.accountsSeason[this.data.accountIndexSeason])
    this.parTicularsForm.itemSeason = a + 1
  },
  // 备注内容的变化回调
  changeBz(e){
    console.log(e)
    console.log(e.detail.value)
    if (e.detail.value.length>30){
      wx.showToast({
        title: '请输入内容，30个字以内',
        icon:"none"
      })
      this.setData({
        bzValue:''
      })
    }else{
      this.parTicularsForm.bz = e.detail.value
      this.parTicularsForm.itemRemark = e.detail.value
    }
  },
  // tba切换
  itemTbas(e){
    console.log(e.currentTarget.dataset.tabs)
    this.setData({
      isShowTabs:e.currentTarget.dataset.tabs,
      isShowHover:e.currentTarget.dataset.tabs
    })
  },
  // 显示录音弹窗
  showRecord(){
    console.log(1)
    this.setData({
      isShowRecord:true
    })
  },
  // 上传图片功能
  showPhoto() {
    wx.chooseImage({
      count: 1,
      success: (img) => {
        const [imgData] = img?.tempFiles || [{}]
        console.log(imgData);
        if (!imgData) {
          wx.showToast({
            icon: 'none',
            title: '没有获取到图片数据',
          })
          return
        }
        if (['jpg', 'jpeg', 'png', 'bmp'].every(item => !imgData?.path?.endsWith(item))) {
          wx.showToast({
            icon: 'none',
            title: '仅支持jpg、png、bmp类型的图片',
          })
          return
        }
        if ((+imgData?.size / 1024 / 1024) > 8) {
          wx.showToast({
            icon: 'none',
            title: '仅支持小于8M的图片',
          })
          return
        }
        uploadAliyun(
          img.tempFilePaths[0],
          (picPath) => {
            if (picPath) {
              this.setData({
                picPath
              })
              this.parTicularsForm.itemImgUrl = picPath
            }
          },
          { directory: 'kejian-space/' }
        )
      },
    })
  },
  // 显示添加编辑框,获取分类标签
  async changeBtn(){
    this.particulars.show()
    const { data } = await request.get(api.getGoodsTabsData)
    console.log(data)
    const a = data.publicLabelList
    a.forEach(i=>{
      i.isShowClass=false
    })
    const b = data.privateLabelList
    b.forEach(i=>{
      i.isdelShowClass = false
    })
    this.setData({
      changeListData:a,
      customTabsItem:b,
      isEditorShow:true,
      openIndex:true
    })
    this.delTabs=[]
    // 判断数组是否有相同的元素，有全部加上边框
    console.log(this.data.userTabData,'用户自带的标签')
    // 在公共标签中 给拥有相同id的对象增加一个类目
    this.data.changeListData.forEach(item=>{
      this.data.userTabData.forEach(v=>{
        if(item.labelId === v.labelId){
          item.isShowClass = true
        }
      })
    })
    // 在自定义标签中，给拥有相同id的对象增加一个类目
    this.data.customTabsItem.forEach(item=>{
      this.data.userTabData.forEach(v=>{
        if(item.labelId === v.labelId){
          item.isdelShowClass = true
        }
      })
    })
    this.setData({
      changeListData:this.data.changeListData,
      customTabsItem:this.data.customTabsItem
    })
    console.log(this.data.changeListData)
    // 清空用户本来的数据列表
    this.data.userTabData = []
  },
  // 选中效果
  changeClass(e){
    const { id } = e.target.dataset
    const { changeListData,customTabsItem } = this.data
    changeListData.find(item=>{
      item.labelId === id && (item.isShowClass = !item.isShowClass)
    })
    customTabsItem.find(item=>{
      item.labelId === id && (item.isdelShowClass = !item.isdelShowClass)
    })
    this.setData({
      changeListData,
      customTabsItem
    })
  },
  // 编辑&保存的点击事件
  async editorBtnChange(){
    this.setData({
      isEditorShow:!(this.data.isEditorShow),
      // delData:[]
    })
    console.log(this.data.delData,'即将处理的数据')
    const { delData, customTabsItem } = this.data
    console.log(delData,'删除元素组成的数据，保存阶段')
    delData.map(item=>{
      this.delTabs.push(item.labelId)
    })
    console.log(this.delTabs,'被选中删除的标签id数组')
    if (this.data.isEditorShow === true){
      console.log('你点击了保存')
      if(this.delTabs.length===0){
      }else{
        const data = await request.post(api.delGoodsTabs,{
          labelIds:this.delTabs
        })
        this.setData({
          delData:[],
        })
        this.delTabs=[]
        console.log(data)
      }
    }
  },
  // 删除图片点击触发的事件 ,将需要删除标签的id储存在一个数组中
  // 同时改变自定义标签的边框，实现选中效果
  delIcom(e){
    const {customTabsItem, delData} = this.data
    console.log(e)
    console.log('我被删除了',e.currentTarget.dataset.id)
    this.setData({
      customTabsItem:this.data.customTabsItem
    })
    console.log(customTabsItem,"自定义数据")
    // 页面删除自定义标签
    // 剩余元素数组
    const newCustomTabsItem = customTabsItem.filter(item=>{
      return item.labelId !== e.currentTarget.dataset.id
    })
    // 当前元素数组
    const newDelDataItem = customTabsItem.find(item=>{
      return item.labelId == e.currentTarget.dataset.id
    })
    delData.push(newDelDataItem)
    console.log(delData,'删除元素组成的数组')
    console.log(newCustomTabsItem,"删除一个指定的元素，剩余的元素数组")
    this.setData({
      customTabsItem:newCustomTabsItem,
      delData
    })
  },
  // 添加标签
  addIconBtn(){
    console.log('下层弹出层显示')
    this.changeTabData()
    console.log('这里置空输入框')
    this.setData({
      dialogShow:true,
      addInputValue:''
    })
  },
  // 输入框监听事件
  addInput(e){
    // console.log(e.detail.value)
    this.setData({
      addInputValue:e.detail.value
    })
  },
//  添加标签弹出层的确定按钮
//  添加自定义标签
  async tapDialogButton(e){
    console.log(this.data.addInputValue)
    if(this.data.addInputValue.length > 10 || this.data.addInputValue.length == 0){
      wx.showToast({
        title: '请输入内容，10个字以内',
        icon:"none"
      })
    }else{
      this.setData({
        dialogShow:false
      })
      const data = await request.post(api.addGoodsTabs,{
        labelName:this.data.addInputValue
      })
      console.log(data)
      if(data.httpStatus === 500){
        return wx.showToast({
          title: data.msg,
          icon:"none"
        })
      }else{
        this.setData({
          dialogShow:false
        })
      }
      this.changeBtn()
    }
  },
  // 点击删除按钮产生的回调
  gospanceXx(){
    console.log(1)
    this.delWin.show()
  },
  // 删除弹出层确定按钮的回调，删除物品
  async confirm(){
    console.log('删除了啊')
    const data = await request.post(api.delGoodsMessage,{
      itemId:this.data.id
    })
    console.log(data)
    console.log(this.parTicularsForm.containerId)
    wx.redirectTo({
      url: `/pages/acceptIndex/acceptIndex?id=${this.parTicularsForm.containerId}`,
    })
  },
  // 点击保存按钮，发送给服务器的数据
  async sendData(){
    const {containerId,spaceId,id,itemImgUrl,bz,labelIdList,itemSeason,itemSex,itemType} = this.parTicularsForm
    console.log('提交表单时候的空间id:',containerId)
    const newitemSeason = parseInt(itemSeason)
    const newitemSex = parseInt(itemSex)
    const newitemType = parseInt(itemType)
    const data = await request.post(api.changeGoodsMessage,{
      containerId,
      id,
      itemImgUrl,
      labelIdList,
      spaceId,
      itemRemark:bz,
      itemSeason:newitemSeason,
      itemSex:newitemSex,
      itemType:newitemType
    })
    console.log(this.parTicularsForm,'最终传输的数据')
    wx.navigateBack({
      delta: 1,
    })
  },
  // 获取物品详情
  async getParticularsData(){
    const { data } = await request.get(api.getGoddsDetails,{
      itemId:this.data.id
    })
    console.log(data)
    this.setData({
      goodsData:data,
      userTabData: data.labelList,
      accountIndex:data.itemType-1,
      accountIndexSex:data.itemSex-1,
      accountIndexSeason:data.itemSeason-1,
      bzValue:data.itemRemark
    })
    const newlabelList = []
    data.labelList.forEach(item=>{
      newlabelList.push(item.labelId)
    })
    this.parTicularsForm.type = data.itemTypeStr
    this.parTicularsForm.sex  =  data.itemSexStr
    this.parTicularsForm.season = data.itemSeasonStr
    this.parTicularsForm.containerId = data.containerId
    this.parTicularsForm.id = data.id
    this.parTicularsForm.labelIdList = newlabelList
    this.parTicularsForm.itemImgUrl = data.itemImgUrl
    this.parTicularsForm.spaceId = data.spaceId
    this.parTicularsForm.itemRemark = data.itemRemark
    this.parTicularsForm.bz = data.itemRemark
    this.parTicularsForm.itemSeason = data.itemSeason
    this.parTicularsForm.itemSex = data.itemSex
    this.parTicularsForm.itemType = data.itemType
    console.log(this.parTicularsForm,'页面刚加载时parTicularsForm的数据')
  },
  // 获取物品信息下拉菜单的所有内容
  async getDownMenuData(){
    const { data } = await request.get(api.getDownMenu)
    // 处理季节数据
    const newitemSeasonList = []
    data.itemSeasonList.map((item)=>{
      newitemSeasonList.push(item.typeName)
    })
    // 处理性别数据
    const newitemSexList = []
    data.itemSexList.map((item)=>{
      newitemSexList.push(item.typeName)
    })
    // 处理类别数据
    const newitemTypeList = []
    data.itemTypeList.map((item)=>{
      newitemTypeList.push(item.typeName)
    })
    this.setData({
      accounts:newitemTypeList,
      accountsSex:newitemSexList,
      accountsSeason:newitemSeasonList
    })
  },
  // 自定义弹出层关闭前的回调
  changeTabData(){
    console.log('弹出层关闭，我走了')
    const { changeListData, customTabsItem,userTabData } = this.data
    console.log('用户关闭弹出层，保留的用户选中的数组',changeListData)
    changeListData.forEach(item=>{
      if (item.isShowClass === true){
        userTabData.push(item)
      }
    })
    customTabsItem.forEach(item=>{
      if (item.isdelShowClass === true) {
        userTabData.push(item)
      }
    })
    userTabData.forEach(item=>{
      delete item.isShowClass
      delete item.isdelShowClass
    })
    this.setData({
      userTabData,
      openIndex:false
    })
    console.log(userTabData)
    const newlabelIdList = []
    userTabData.forEach(item=>{
      newlabelIdList.push(item.labelId)
    })
    console.log(newlabelIdList)
    this.parTicularsForm.labelIdList = newlabelIdList
  },
  // 空间标题改变监听事件
  picChangeSpance(e){
    console.log(e)
    this.parTicularsForm.spaceId = e.detail.data.id
    console.log(this.parTicularsForm.spaceId)
    this.setData({
      goodsTitleIndex:0
    })
    this.getGoodsData(e.detail.data.id)
  },
  // 容器标题改变监听事件
  picChangeGodds(e){
    console.log(e.detail.data.id,'当前容器的id')
    this.parTicularsForm.containerId = e.detail.data.id
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.parTicularsForm = {}
    this.setData({
      id:options.id
    })
    this.getParticularsData()
    this.getDownMenuData()
    this.getSpanceData()
    console.log(options.spanceid)
    console.log('我将要去点击空间第一个')
    this.getGoodsData(options.spanceid)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.particulars = this.selectComponent('#particulars')
    this.delWin = this.selectComponent('#delWin')
    this.getParticularsData()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage(e) {
    return shareOptions('default',e)
  },
})